package org.luosl.webmagicx.cli

import org.apache.commons.cli.{CommandLine, DefaultParser, Options}

/**
  * Created by luosl on 2017/12/15.
  */
case class Cli(args:String*) {

  val options:Options = new Options()
    .addOption("host", true, "host")
    .addOption("confPath", true, "爬虫配置文件/目录路径")
    .addOption("port", true, "http监听端口")
    .addOption("spiderId", true, "爬虫id")

  private val cli: CommandLine = {
    val p:DefaultParser = new DefaultParser()
    p.parse(options,args.toArray)
  }

  def optionVal(key:String):String = {
    if(cli.hasOption(key)){
      cli.getOptionValue(key)
    }else{
      throw new NoSuchElementException(s"无效的key:$key")
    }
  }

  def cliArgs:Array[String] = cli.getArgs

  def optionValOrDefault(key:String,defVal:String):String = optionValOpt(key).getOrElse(defVal)

  def optionValOpt(key:String):Option[String] = {
    if(cli.hasOption(key)){
      Option(cli.getOptionValue(key))
    }else{
      Option.empty[String]
    }
  }

}
